package com.tuanzi.loan.core.service;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.data.domain.Sort;

import com.tuanzi.loan.core.entity.BaseEntity;
import com.tuanzi.loan.core.repository.JPABaseRepository;

/**
 * @author Ray 2017/09/21
 */

public abstract class BaseServiceImpl<T extends BaseEntity, PK extends Serializable> implements BaseService<T, PK> {

	protected abstract JPABaseRepository<T, PK> getRepository();

	@Override
	public T disable(final T t) {
		t.setEnable(false);
		return this.saveOrUpdate(t);
	}

	@Override
	public List<T> findAll() {
		return getRepository().findAll();
	}

	@Override
	public List<T> findAll(Sort sort) {
		return getRepository().findAll(sort);
	}

	@Override
	public T findOne(final PK id) {
		return getRepository().findOne(id);
	}

	@Override
	public T saveOrUpdate(final T t) {
		return getRepository().save(t);
	}

	@Override
	public Boolean exists(PK id) {
		return getRepository().exists(id);
	}

	@Override
	public List<T> saveOrUpdate(List<T> t) {
		return t.parallelStream().map(this::saveOrUpdate).collect(Collectors.toList());
	}

	@Override
	public List<T> disable(List<T> entities) {
		return entities.parallelStream().map(this::disable).collect(Collectors.toList());
	}

	@Override
	public List<T> enable(List<T> entities) {
		return entities.parallelStream().map(this::enable).collect(Collectors.toList());
	}

	@Override
	public T enable(T t) {
		t.setEnable(true);
		return this.saveOrUpdate(t);
	}

	@Override
	public List<T> findAll(List<PK> ids) {
		return getRepository().findAll(ids);
	}

	@Override
	public List<T> findAllEnable() {
		return getRepository().findAllByEnableTrue();
	}

	@Override
	public List<T> findAllDisable() {
		return getRepository().findAllByEnableFalse();
	}

	@Override
	public void delete(T t) {
		getRepository().delete(t);
	}

	@Override
	public void delete(List<T> entities) {
        getRepository().delete(entities);
	}
}
